#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年4月29日

@author: chenyongbing
'''
import sys,os,re,datetime
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

sys.path.append('../../')
from base.time_method import myTimeMethod
from base.retail_datas import myRetailDatas
groups = myRetailDatas.get_groups_by_comp(tab, comp_id, comp_group)


groups = {"32011278":"北京门店1",
"32011279":"北京门店2",
"32011280":"北京门店3",
"32011511":"北京门店4",
"32011512":"北京门店5",
"32011513":"北京门店6"}
import json,tarfile
import logging

def openTarFile(rawfile_tar):
    output = ''
    if not os.path.exists(rawfile_tar):
        logging.error('file %s not exists.'%rawfile_tar)
        return output
    #tar = tarfile.open(rawfile_tar)
    try:
        tar = tarfile.open(rawfile_tar)
        
    except :
        logging.error('tar file error.')
        return output
    for member in tar.getmembers():
        f = tar.extractfile(member)
        out = f.read()
        output = output + out+'\n'
    tar.close()
    return output



def create_pusher_data(groups=[],tarPath='/data/zmexport/rawdata/rawdata_group/',startTime=None,endTime=None,export_name='wp_pusher'):
    if startTime==None:
        startTime = (datetime.date.today() - datetime.timedelta(1)).strftime('%Y-%m-%d')
    if endTime == None:
        endTime = (datetime.date.today() - datetime.timedelta(1)).strftime('%Y-%m-%d')  
    
    days = myTimeMethod.get_slist_between_st_et(startTime, endTime)
    today = (datetime.date.today()).strftime('%Y-%m-%d')  
    export_file = os.path.join(current_dir,'../report/%s.%s.txt'%(export_name,today))
    fr = open(export_file,'w')
    
    for day in days:
        for group in groups:
            group_name = groups[group]
            raw_tarfile = tarPath+day+'/%s.txt.tar.gz'%group
            if not os.path.exists(raw_tarfile):continue
            output = openTarFile(raw_tarfile)
            datas = []
            for line in output.split('\n'):
                lineList = line.split('.')
                if len(lineList)!=6:continue
                day = lineList[0]
                device = lineList[1]
                if len( device)>12:continue
                mac = lineList[2]
                stime = lineList[3]
                rssi = lineList[4]
                data = {"Device":device,"MAC":mac,"RSSI":rssi,"Time":"%s %s"%(day,stime)}
                datas.append(data)
                if len(datas)>=10:
                    msg = json.dumps({"MacList":[{"GroupId":group,"GroupName":group_name,"List":datas}],"Type":1})
                    fr.write(msg.encode("utf-8")+'\n')
                    datas = []
            if len(datas)!=0:
                print group,group_name,datas
                msg = json.dumps({"MacList":[{"GroupId":group,"GroupName":group_name,"List":datas}],"Type":1})    
                fr.write(msg.encode('utf-8')+'\n')



    fr.close()
    
    
# dir = '../source'
# fr = open('../source/wp_pusher-2015053.txt','w')
# for wpdir in os.listdir(dir):
#     if not re.search('wp-2015053',wpdir):continue
#     print wpdir
#     for wpgroup in os.listdir(dir+'/'+wpdir):
#         if not re.search('.txt$',wpgroup):continue
#         #print wpfile
#         
#         group = re.sub('.txt','',wpgroup)
#         group_name = groups[group]
#         print group , group_name,type(group_name)
#         datas = []
#         for wpfile in os.listdir(dir+'/'+wpdir+'/'+wpgroup):
#             out = open(dir+'/'+wpdir+'/'+wpgroup+'/'+wpfile).read()
#             for line in out.split('\n'):
#                 lineList = line.split('.')
#                 if len(lineList)!=6:continue
#                 day = lineList[0]
#                 device = lineList[1]
#                 if len( device)>12:continue
#                 mac = lineList[2]
#                 stime = lineList[3]
#                 rssi = lineList[4]
#                 data = {"Device":device,"MAC":mac,"RSSI":rssi,"Time":"%s %s"%(day,stime)}
#                 datas.append(data)
#                 if len(datas)>=10:
#                     msg = json.dumps({"MacList":[{"GroupId":group,"GroupName":group_name,"List":datas}],"Type":1})
#                     
#                     
#                     fr.write(msg.encode("utf-8")+'\n')
#                     datas = []
#         if len(datas)!=0:
#             print group,group_name,datas
#             msg = json.dumps({"MacList":[{"GroupId":group,"GroupName":group_name,"List":datas}],"Type":1})
#                     
#             fr.write(msg.encode('utf-8')+'\n')
# fr.close()





if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--groups', metavar=u'groups', required=True)
    parser.add_argument('--startTime' ,  metavar=u'start time', default=None)
    parser.add_argument('--endTime',metavar=u'endtime ',default=None)
    parser.add_argument('--export_name',metavar=u'export name ',default='wp_pusher')
    parser.add_argument('--tar_path',metavar='tarPath',default='/data/zmexport/rawdata/rawdata_group/')
    args = parser.parse_args()
    
    groups = args.groups.split(',')
    startTime = args.startTime
    endTime = args.endTime
    export_name = args.export_name
    tarPath = args.tar_path
    create_pusher_data(groups=groups,tarPath=tarPath,startTime=startTime,endTime=endTime,export_name=export_name)
    
    